import logging
import subprocess
from kubernetes import config
from kubernetes import client


def get_vmrules(namespace: str, kubeconfig_path: str = None):
    """
    Retrieve all VMRule resources in a specified namespace.

    Args:
        namespace (str): The namespace from which to fetch VMRule resources.
        kubeconfig_path (str, optional): The path to the Kubernetes config file. Defaults to None.

    Returns:
        list: A list of VMRule resources (as dictionaries) if successful, or an empty list if an error occurs.
    """
    # Load the Kubernetes configuration, using the specified path if provided
    if kubeconfig_path:
        config.load_kube_config(config_file=kubeconfig_path)
    else:
        config.load_kube_config()

    # Set up the CustomObjectsApi for custom resource definitions (CRDs)
    api_instance = client.CustomObjectsApi()
    group = "operator.victoriametrics.com"  # Group of the CRD
    version = "v1beta1"  # API version of the CRD
    plural = "vmrules"  # Plural name of the CRD
    vmrules_name = []
    try:
        # Fetch the VMRule resources from the specified namespace
        vmrules = api_instance.list_namespaced_custom_object(
            group=group, version=version, namespace=namespace, plural=plural
        )
        vmrule_items = vmrules.get("items")
        for vmrule in vmrule_items:
            vmrules_name.append(vmrule["metadata"]["name"])
        return vmrules_name
    except client.exceptions.ApiException as e:
        logging.error(f"An error occurred: {e}")
        return []

def run_command(command):
    try:
        logging.info(f"Running command: {command}")
        result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return result
    except subprocess.CalledProcessError as error:
        return f"Error: {error.stderr.decode('utf-8')}"
